﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FbKPI.Model;
using FbKPI.Facade;
using FbKPI.Facade.Validator;
using System.Web.Script.Serialization;
using System.Collections.ObjectModel;
using System.Web.Script.Services;
using System.Transactions;

namespace FBKPI.ProcessRequest
{
    /// <summary>
    /// Summary description for PickAvailableKPIHandler
    /// </summary>
    public class PickAvailableKPIHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            string msg = this.Save();
            context.Response.Write(msg);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string Save()
        {
            string msg = "OK";
            //int ID = Convert.ToInt16(HttpContext.Current.Request.QueryString["KPI"]);
            string action = HttpContext.Current.Request.QueryString["action"];
            Employee CurrUser = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(HttpContext.Current.Request.QueryString["User"]));

            string[] KpiIDs = HttpContext.Current.Request.QueryString["KpiIDs"].ToString().Trim().Split(',');
            

            KPIFacade df = new KPIFacade();
            //KPI KPIs = df.GetKPIByID(ID);

            //KPIAssign Existing = new KPIAssignFacade().GetAllKPIAssignsByKPIID(ID).Where(x => x.CreateBy == CurrUser.Email && x.isActive &&
            //    x.SubBranch.ID == CurrUser.SubBranch.ID && x.Verifier.ID == CurrUser.ID && x.Weight == KPIs.Weight).FirstOrDefault();

            //KPIAssign Existing = new KPIAssignFacade().GetAllKPIAssignsByKPIID(ID).Where(x =>  x.isActive &&
            //  x.SubBranch.ID == CurrUser.SubBranch.ID && x.Weight == KPIs.Weight).FirstOrDefault();

            sysLogFacade sysLogFacade = new sysLogFacade();
            sysLog objSysLog = new sysLog();
            List<KPIAssign> listKPIAssign = new List<KPIAssign>();
            switch (action)
            {
                case "pick": 
                    //if (Existing == null)
                    //{

                    foreach (string KpiID in KpiIDs)
                    {
                      KPI  KPIs = df.GetKPIByID(Convert.ToInt32(KpiID));
                        if (KPIs != null)
                        {
                            KPIAssign ka = new KPIAssign()
                            {
                                ID = 0,
                                isActive = true,
                                KPI = KPIs,
                                Location = CurrUser.SubBranch.Location,
                                ManualCalculation = KPIs.ManualCalculation,
                                Polarization = KPIs.Polarization,
                                RGM = CurrUser.SubBranch.Location.RGM,
                                SubBranch = CurrUser.SubBranch,
                                UoM = KPIs.UoM,
                                UoMDetailMax = KPIs.UoMDetailMax,
                                UoMDetailMin = KPIs.UoMDetailMin,
                                UoMEnableFlag = KPIs.UoMEnableFlag,
                                Verifier = CurrUser,
                                Weight = KPIs.Weight,
                                WeightEnableFlag = KPIs.WeightEnableFlag,
                                CreateBy = CurrUser.Email
                            };

                            listKPIAssign.Add(ka);
                        }
                    }
                        

                        //WeightValidator wv = new WeightValidator();
                        //msg = wv.ValidateWeight(CurrUser, ka, KPIs.Year);

                        //if (msg == "OK")
                        //{
                            try
                            {
                                //using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
                                //{
                                //    KPIAssignFacade kaf = new KPIAssignFacade();
                                //    msg = kaf.Save(ka);
                                //    trans.Complete();
                                //    trans.Dispose();
                                //}

                                KPIAssignFacade kaf = new KPIAssignFacade();
                                if (kaf.SaveWithList(listKPIAssign))
                                    msg = "Transaction Success";
                                else
                                    msg = "Transaction Failed";

                                objSysLog.Description ="Pick kpi sukses !";
                            }
                            catch (Exception ex)
                            {
                                objSysLog.Description = ex.Message;
                            }

                            objSysLog.LogEvent = "Pick KPI";
                            objSysLog.Source = "PickAvailableKPIHandler.ashx";
                            objSysLog.CreatedBy = CurrUser.Email;
                            objSysLog.CreatedDate = DateTime.Now;

                            sysLogFacade.Save(objSysLog);
                            

                        //}
                    //}        
                    break;

                case "unpick":
                    bool assignKpi = false;
                    //List<KPIAssignDetail> listDetail = new List<KPIAssignDetail>();
                    listKPIAssign = new List<KPIAssign>();
                    try
                    {
                        foreach (string KpiId in KpiIDs)
                        {
                            IList<KPIAssignDetail> objDetail = new KPIAssignDetailFacade().GetKPIAssignDetailByKPIAssignID(Convert.ToInt32(KpiId));
                            if (objDetail != null && objDetail.Count > 0)
                            {
                                msg = "KPI tidak dapat di Unpick,masih ada Assign pada KPI tersebut!";
                                assignKpi = true;
                                break;
                            }
                        }

                        if (!assignKpi)
                        {
                           foreach(string KpiId in KpiIDs)
                           {
                               KPIAssign obj = new KPIAssign();
                               obj.ID = Convert.ToInt32(KpiId);
                               listKPIAssign.Add(obj);
                           }

                           KPIAssignFacade kaf = new KPIAssignFacade();
                           if (kaf.DeleteWithList(listKPIAssign))
                               msg = "Transaction Success";
                           else
                               msg = "Transaction Failed";

                        }

                        objSysLog.Description = "UnPick kpi sukses !";
                    }
                    catch(Exception ex)
                    {
                        objSysLog.Description = ex.Message;
                    }

                    objSysLog.LogEvent = "UnPick";
                    objSysLog.Source = "PickAvailableKPIHandler.ashx";
                    objSysLog.CreatedBy = CurrUser.Email;
                    objSysLog.CreatedDate = DateTime.Now;
                    sysLogFacade.Save(objSysLog);

                    //try
                    //{
                    //    IList<KPIAssignDetail> ExistingDetail = new KPIAssignDetailFacade().GetKPIAssignDetailByKPIAssignID(ID);
                    //    if (ExistingDetail != null && ExistingDetail.Count > 0)
                    //    {
                    //        msg = "KPI tidak dapat di Unpick,masih ada assign detail pada KPI tersebut!";
                    //    }
                    //    else
                    //    {
                    //        msg = new KPIAssignFacade().Delete(Existing);
                    //    }

                    //    objSysLog.Description = "UnPick kpi sukses !";
                    //}
                    //catch(Exception ex)
                    //{
                    //    objSysLog.Description = ex.Message;
                    //}

                    //objSysLog.LogEvent = "UnPick";
                    //objSysLog.Source = "PickAvailableKPIHandler.ashx";
                    //objSysLog.CreatedBy = CurrUser.Email;
                    //objSysLog.CreatedDate = DateTime.Now;
                    //sysLogFacade.Save(objSysLog);
                          
                        
                    break;
                default: break;
            }

            return msg;
        }
    }
}